package com.xyy.saas.payment.util.mq;

import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.pingxx.domain.RefundDO;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.RocketMqGroup;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.cores.vo.CallbackResultVo;
import com.xyy.saas.payment.dao.mapper.RefundOrderMapper;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.payment.core.service.PaymentService;
import com.xyy.saas.payment.util.JSONUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangtianqi
 * @date 2019/12/4 11:20
 */
@Service
@RocketMQMessageListener(topic = RocketMqTopic.TOPIC_REFUND_CHANGE_STATUS, consumerGroup = RocketMqGroup.TOPIC_REFUND_CHANGE_STATUS, consumeMode = ConsumeMode.ORDERLY)
public class RefundChangeStatusConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(RefundChangeStatusConsumer.class);

    @Autowired
    MqProducer mqProducer;

    @Autowired
    PaymentService paymentService;

    @Autowired
    RefundOrderMapper refundOrderMapper;

    @Autowired
    CallbackRunner callbackRunner;

    @Override
    public void onMessage(MessageExt message) {
        String body = new String(message.getBody());
        try {
            LOGGER.info("RetryRefundConsumer#onMessage body:{}", body);
            RefundDO refundDO = JSONUtils.parse2Object(body, RefundDO.class);
            RefundOrder refundOrder = refundOrderMapper.selectByChannelRefundNo(refundDO.getPayNo(), refundDO.getId());
            if(refundDO.getSucceed()) {
                if(refundOrder == null) {
                    LOGGER.error("RefundChangeStatusConsumer#onMessage refund not found error refundDO Id:{}", refundDO.getId());
                    return;
                }
                refundOrder.setStatus(RefundOrder.STATUS_FINISH);
                refundOrder.setSuccessTime(refundDO.getTimeSucceed());
            } else {
                // 退款失败
                LOGGER.error("RefundChangeStatusConsumer#callBackHandler refund status not success refundDO:{}", JSON.toJSONString(refundDO));
                if(RefundOrder.STATUS_FAIL.equals(refundDO.getStatus())) {
                    refundOrder.setStatus(refundDO.getStatus());
                } else if(RefundOrder.STATUS_CLOSED.equals(refundDO.getStatus())) {
                    refundOrder.setStatus(refundDO.getStatus());
                } else {
                    // 无法识别的状态
                    LOGGER.error("OrderRefundSuccessHandler#callBackHandler refund status not found refundDO:{}", JSON.toJSONString(refundDO));
                    return;
                }
            }
            int count = refundOrderMapper.updateStatusByRefundNo(refundOrder.getRefundNo(), refundOrder.getChannelRefundNo(), refundOrder.getSuccessTime(), refundOrder.getUpdateTime(), refundOrder.getStatus(), refundOrder.getChannelTransactionNo(), refundOrder.getVersion());
            if(count < 1) {
                LOGGER.error("RefundChangeStatusConsumer#onMessage update sql error refundDO:{}", JSON.toJSONString(refundDO));
            }
            if(refundDO.getSucceed()) {
                // 异步回调
                Long unixTime = refundOrder.getSuccessTime().getTime()/1000;
                callbackRunner.callback(refundDO.getOrderNo(), CallbackResultVo.TYPE_REFUND_SUCCESS, refundOrder.getAmount(),0, unixTime, refundOrder.getCallbackAddress());
            } else {
                // 异步回调
                callbackRunner.callback(refundDO.getOrderNo(), CallbackResultVo.TYPE_REFUND_FAIL, refundOrder.getAmount(),0, 0L, refundOrder.getCallbackAddress());
            }
        } catch (Exception e) {
            LOGGER.error("RefundChangeStatusConsumer#onMessage consumer error body:{}", body, e);
        }
    }


    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        consumer.setConsumeTimestamp(UtilAll.timeMillisToHumanString3(System.currentTimeMillis()));
    }
}